package com.leenmvc.core.utils;

import com.leenmvc.core.dao.mysql.connect.DbConfig;
import com.leenmvc.core.dao.mysql.connect.DbConfigList;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.utils.spring.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MysqlImportUtil {
    private final static Logger logger = LoggerFactory.getLogger(MysqlImportUtil.class);
    private static String host ;
    private static String port ;
    public static String dbName ;
    private static String username ;
    private static String passwd ;


    static {
        DbConfigList dbConfigList = SpringContextUtils.getBean(DbConfigList.class);
        DbConfig dbConfig = dbConfigList.getC3p().get(0);
        String str = dbConfig.getJdbcUrl();
        host = str.substring(13, str.lastIndexOf(":"));
        port = str.substring(str.lastIndexOf(":")+1, str.indexOf("/", str.lastIndexOf(":")));
        dbName = str.substring(str.lastIndexOf("/", str.indexOf("?"))+1, str.indexOf("?"));
        username = SpringContextUtils.getStr("c3p0.user");
        passwd = SpringContextUtils.getStr("c3p0.password");
    }
    /**
     * 备份
     */
    public static void backup(String filePath) throws InterruptedException, IOException {
        String osName = System.getProperty("os.name");
        String commend;
        if (osName.toLowerCase().contains("windows")){
             commend = "cmd /c mysqldump -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " " + dbName + " > " + filePath;
        }else {
             commend = "mysqldump -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " " + dbName + " > " + filePath;
        }

        Process exec = Runtime.getRuntime().exec(commend);
        InputStream errorStream = exec.getErrorStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
        String line;
        while ((line = reader.readLine()) != null) {
            logger.info(line);
        }
        exec.waitFor();
        logger.info("数据库备份成功,备份路径为：" + filePath);
    }




    /**
     * 备份恢复
     */
    public static void load(String filePath) throws InterruptedException, IOException {
        String osName = System.getProperty("os.name");
        String commend;
        String delectCommend;
        String createCommend;
        if (osName.toLowerCase().contains("windows")){
            delectCommend = "cmd /c mysqladmin -f  -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " drop "+ dbName;
            createCommend = "cmd /c mysqladmin -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " create "+ dbName;
            commend = "cmd /c mysql -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " " + dbName +" < "+filePath;
        }else {
            delectCommend = "mysqladmin -f  -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " drop "+ dbName;
            createCommend = "mysqladmin -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " create "+ dbName;
            commend = "mysql -h" + host + " -P"+port+" -u" + username + " -p" + passwd + " " + dbName +" < "+filePath;
        }
        execCommend(delectCommend);
        execCommend(createCommend);
        execCommend(commend);

    }

    public static void execCommend(String commend) throws InterruptedException, IOException {
        //拼接cmd命令
        Process exec = Runtime.getRuntime().exec(commend);
        InputStream errorStream = exec.getErrorStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
        String line;
        while ((line = reader.readLine()) != null) {
            logger.info(line);
        }
        if( exec.waitFor() == 0){
            logger.info("执行命令成功："+commend);
        }
    }

    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        URL url = null;
        try {
            url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);

            return conn.getInputStream();
        } catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("文件不存在或网络异常");
        }
    }


}
